package com.atguigu.guli.service.edu.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.guli.service.edu.entity.Subject;
import com.atguigu.guli.service.edu.entity.excel.ExcelSubjectData;
import com.atguigu.guli.service.edu.mapper.SubjectMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@NoArgsConstructor
public class ExcelSubjectDataListener extends AnalysisEventListener<ExcelSubjectData> {

    //假设这个是一个DAO，当然有业务逻辑这个也可以是一个service，当然如果不用存储这个对象没用
    private SubjectMapper subjectMapper;
    public  ExcelSubjectDataListener(SubjectMapper subjectMapper){
        this.subjectMapper = subjectMapper;
    }

    @Override
    public void invoke(ExcelSubjectData excelSubjectData, AnalysisContext analysisContext) {
        // 每次读取一行数据会被调用一次,将本次的数据存储到数据库
        String levelOneTitle = excelSubjectData.getLevelOneTitle();
        String levelTwoTitle = excelSubjectData.getLevelTwoTitle();

        // 判断如果一级分类没有，保存一级课程分类
        LambdaQueryWrapper<Subject> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Subject::getTitle,levelOneTitle);
        queryWrapper.eq(Subject::getParentId,0);
        Subject subject = subjectMapper.selectOne(queryWrapper); //判断是否存在唯一的一级title

        if (subject == null){
            subject = new Subject();
            subject.setParentId("0");
            subject.setTitle(levelOneTitle);
            subject.setSort(0);
            subjectMapper.insert(subject);
        }
        //保存二级课程分类
        queryWrapper.clear();
        queryWrapper.eq(Subject::getTitle,levelTwoTitle);
        queryWrapper.eq(Subject::getParentId,subject.getId());

        Integer count = subjectMapper.selectCount(queryWrapper);
        if (count == 0){
            Subject subject1 = new Subject();
            subject1.setSort(0);
            subject1.setTitle(levelTwoTitle);
            subject1.setParentId(subject.getId());
            subjectMapper.insert(subject1);
        }

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        System.out.println("excel文档解析完成");
    }
}
